<template>
  <div v-if="tocreateDemoVisible">
    <a-empty>
      <span slot="description"> 暂无示例数据 </span>
      <a-button v-if="hasEditPermission" type="primary" @click="onCreateDemoDate()">
        点击生成</a-button
      >
    </a-empty>
  </div>

  <div v-else>
    <DsWorkToolbar :miniTopBar="miniTopBar" @collapse="handleCollapse">
      <template #left>
        <a-button v-if="hasEditPermission" :size="btnSize" @click="onAdd()">新增</a-button>
        <a-button v-if="hasEditPermission" :size="btnSize" @click="onCreateDemoDate()"
          >更新示例数据</a-button
        >
      </template>
      <template #right>
        <a-button v-if="hasEditPermission" type="primary" :size="btnSize" @click="onSave()"
          >保存</a-button
        >
      </template>
    </DsWorkToolbar>

    <!-- <div class="tool-btn">
      <div class="left-btn">
        <a-button v-if="hasEditPermission" @click="onAdd()">新增</a-button>
        <a-button v-if="hasEditPermission" style="margin-left: 10px" @click="onCreateDemoDate()"
          >更新示例数据</a-button
        >
      </div>

      <div class="right-btn">
        <a-button v-if="hasEditPermission" type="primary" @click="onSave()">保存</a-button>
      </div>
    </div> -->

    <!-- <div class="header">
      <a-button v-if="hasEditPermission" type="primary" @click="onSave()">保存</a-button>
    </div>

    <div class="tool-btn">
      <a-button v-if="hasEditPermission" size="small" @click="onAdd()">新增</a-button>
      <a-button
        v-if="hasEditPermission"
        size="small"
        style="margin-left: 10px"
        @click="onCreateDemoDate()"
        >更新示例数据</a-button
      >
    </div> -->

    <ds-global-list
      ref="refList"
      :columns="tableColumns"
      :request="asyncData"
      pagination="false"
      @demoDatasubmit="demoDatasubmit"
      vmode="table"
      :vmodeData="['table']"
      :rowKey="columnOpt.rowKey"
    >
      <span v-for="column in tableColumns" :slot="column.dataIndex" :key="column.dataIndex">
        <div>
          {{ column.rawTitle }}
          <span style="color: red" v-if="column.type == 'deleted'" class=""> (已删除)</span>
          <span style="color: blue" v-else-if="column.type == 'add'" class=""> (新增)</span>
        </div>
      </span>

      <template slot="operation" slot-scope="text, record">
        <a href="javascript:;" v-if="hasEditPermission" @click="onEdit(record)"> 编辑 </a>

        <a-popconfirm
          placement="topRight"
          title="是否确认删除？"
          @confirm="() => onDelete(record[columnOpt.rowKey], record)"
        >
          <a v-if="hasEditPermission" href="javascript:;">删除</a>
        </a-popconfirm>
      </template>
    </ds-global-list>

    <FormModal
      v-if="formModelParams"
      visible
      :resourceId="curResourceId"
      :record="formModelParams.resourceItem"
      isdemoData="true"
      v-bind="{
        ...(formModelParams.resourceItem && {
          rowKeyId: formModelParams.resourceItem[columnOpt.rowKey],
        }),
        ruleData: formModelParams.resourceItem
          ? columnAllConfig.ruleData
          : sett.getFillDefaultValueData1(columnAllConfig.ruleData, formModelParams.resourceItem, {
              relationMap,
              columnOpt,
              isEdit: !!formModelParams.resourceItem,
              context: this,
            }),
      }"
      @cancel="formModelParams = null"
      @ok="
        () => {
          $refs.refList.refresh();
          formModelParams = null;
        }
      "
      @demoDatasubmit="demoDatasubmit"
    >
    </FormModal>
  </div>
</template>
<script>
import { DsGlobalList, DsModal, DsWorkToolbar } from "@daas/components";
import { toCamelCase } from "@lib/attribute-editor/modal/helper";
import EditableCell from "@lib/common/components/EditableCell.vue";
import * as sett from "@daas/components/es/ds-spreadsheet/spreadsheet-resource-list/setting.js";
import FormModal from "@daas/components/es/ds-form-model/modal.vue";
import { request } from "@daas/core";

export default {
  name: "demo111",
  props: {
    detailData: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {
    DsGlobalList,
    EditableCell,
    FormModal,
    DsModal,
    DsWorkToolbar,
  },
  data() {
    return {
      demoJsonDataEntity: {},
      record: {},
      tocreateDemoVisible: false,
      toUpdateDemoVisible: false,
      sett,
      formModelParams: null,
      columnAllConfig: null,
      miniTopBar: false,
      btnSize: "default",
    };
  },
  computed: {
    tableColumns() {
      var result = [];
      var columnDisplayNames = this.demoJsonDataEntity.columnDisplayNames;
      var columnNames = this.demoJsonDataEntity.columnNames;

      let columnsOfDetail = this.detailData.columns;
      let columnNamesOfDetail = columnsOfDetail.map((it) => it.name);

      for (var i = 0; i < columnNames.length; i++) {
        let type = "normal";
        if (!columnNamesOfDetail.includes(columnNames[i])) {
          type = "deleted";
        }
        let column = {
          rawTitle: columnDisplayNames[i],
          dataIndex: columnNames[i],
          slots: { title: columnNames[i] },
          type: type,
        };
        result.push(column);
      }

      let addColumns = columnsOfDetail.filter((item) => !columnNames.includes(item.name));
      addColumns.forEach((element) => {
        let column = {
          rawTitle: element.displayName,
          dataIndex: element.name,
          slots: { title: element.name },
          type: "add",
        };
        result.push(column);
      });

      let operation = {
        title: "操作",
        dataIndex: "operation",
        width: 90,
        scopedSlots: { customRender: "operation" },
        fixed: "right",
      };
      result.push(operation);
      return result;
    },
    curResourceId() {
      return this.detailData?.resourceId;
    },
    columnOpt() {
      const { columnAllConfig } = this;
      return columnAllConfig ? columnAllConfig.columnOpt : {};
    },
    hasEditPermission() {
      return (
        (this.detailData.behaviors || []).find((item) => item.code === "editData") ||
        this.isCreateTable
      );
    },
  },
  methods: {
    async asyncData(params) {
      const { pageIndex, limit } = params.pageParam;

      const arr = [...this.demoJsonDataEntity.rows];
      let res = {
        data: arr.splice((pageIndex - 1) * limit, pageIndex * limit),
        pageParam: {
          ...params.pageParam,
          recordTotal: this.demoJsonDataEntity.rows.length,
          pageTotal: this.demoJsonDataEntity.rows.length / limit,
        },
      };

      return await res;
    },
    onDelete(key) {
      let rows = this.demoJsonDataEntity.rows;
      this.$set(
        this.demoJsonDataEntity,
        "rows",
        rows.filter((item) => item[this.columnOpt.rowKey] !== key),
      );
      this.$refs.refList.refresh();
    },
    onAdd() {
      this.formModelParams = {};
    },
    onEdit(record) {
      const currentRecord = record;
      if (currentRecord) {
        this.formModelParams = { resourceItem: currentRecord };
      }
    },

    demoDatasubmit(value, isEdit) {
      let rows = this.demoJsonDataEntity.rows;
      if (isEdit) {
        this.$set(
          this.demoJsonDataEntity,
          "rows",
          rows.map((item) => {
            return value[this.columnOpt.rowKey] === item[this.columnOpt.rowKey] ? value : item;
          }),
        );
      } else {
        rows.push(value);
      }
      this.$refs.refList.refresh();
      this.formModelParams = null;
    },

    async onSave() {
      let demoDataJson = JSON.stringify(this.demoJsonDataEntity);
      this.detailData.demoDataJson = demoDataJson;
      await request.post("/api/daasMeta/SaveRDBStructuredDataResourceV2", this.detailData);
      this.$emit("refresh");
    },

    onCellChange(key, dataIndex, value) {
      const rows = this.demoJsonDataEntity.rows;
      const target = rows.find((item) => item.id === key);
      if (!target) return;
      target[dataIndex] = value;

      return;
    },
    async onCreateDemoDate() {
      let res = await request.post("/api/daasDMS/CreateDemoResourceData", {
        gainOnly: "data",
        pageParam: {
          pageIndex: 1,
          limit: 10,
          sortField: "",
          sortType: "",
        },
        dataResourceId: this.detailData.resourceId,
        rowType: "map",
      });
      if (res) {
        this.demoJsonDataEntity = res;
      }
      this.tocreateDemoVisible = false;
      this.$refs.refList.refresh();
    },
    handleCollapse(bool) {
      this.miniTopBar = bool;
      this.btnSize = bool ? "small" : "default";
    },
  },

  async created() {
    if (this.detailData.demoDataJson) {
      this.demoJsonDataEntity = JSON.parse(this.detailData.demoDataJson);
    } else {
      this.tocreateDemoVisible = true;
    }

    const customProps = {
      resourceInfo: this.detailData,
      showAllcolumn: true,
      showUpdateAction: true,
    };
    this.columnAllConfig = await sett.getColumnAllConfig(this.detailData, customProps, this);
  },
};
</script>
<style lang="less" scoped>
// .header {
//   position: sticky;
//   top: 0;
//   z-index: 3;
//   display: flex;
//   justify-content: flex-end;
// }
// .tool-btn {
//   margin-bottom: 16px;
// }

.tool-btn {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}
.right-btn {
  display: flex;
  justify-content: flex-end;
}
</style>
